package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"log"
	"myserver/controller"
	"myserver/tool"
	"net/http"
	"os"
)

func main() {
	var cfg, err = tool.ParseConfig("./config/app.json")
	//InitConfig() //读取yml中的配置 由于用的json配置 这里只是测试 不使用此方法
	if err != nil {
		panic(err)
	}
	_, err = tool.OrmEngine(cfg)
	if err != nil {
		fmt.Println("err = ", err)
		return
	}
	app := gin.Default()
	//实例化redis配置
	//tool.InitRedisStore()
	//设置全局跨域访问
	app.Use(Cors())
	//路由
	registerRouter(app)
	app.Run((*cfg).AppHost + ":" + (*cfg).AppPort)
}

//路由设置
func registerRouter(routers *gin.Engine) {
	//保护路由
	//router := routers.Group("/api", middleware.AuthMiddleware())
	router := routers.Group("/api")
	new(controller.UserController).Router(routers)
	new(controller.FamilyController).Router(router)
	new(controller.HouseController).Router(router)
	new(controller.SubsidyController).Router(router)
	new(controller.WorkController).Router(router)
	new(controller.ReservationController).Router(router)
	new(controller.TitleController).Router(router)
}

//读取yml中的配置 由于已经使用读取json中的配置 这里只是学习
func InitConfig() {
	workDir, err := os.Getwd()
	viper.SetConfigName("application")
	viper.SetConfigType("yml")
	viper.AddConfigPath(workDir + "/config")
	err = viper.ReadInConfig()
	if err != nil {
		log.Println("err = ", err)
		return
	}
}

// 处理跨域请求,支持options访问
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
		c.Header("Access-Control-Allow-Headers", "*")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		// 处理请求
		c.Next()
	}
}
